package main

import (
	"fmt"
	"sync"
	"time"
)

func init() {
	//mains()
}

/**
 * 写成在协程未执行完成前不能结束主进程
 */
func mains() {
	//1.通道
	ChanData := make(chan int, 3)
	go func() {
		for i := 0; i < 10; i++ {
			fmt.Printf("往里面送数据，值：%v\n", i)
			ChanData <- i
		}
	}()

	go func() {
		for i := 0; i < 10; i++ {
			data := <-ChanData
			fmt.Printf("往外面推数据，值：%v\n", data)
			time.Sleep(time.Second)
		}
	}()

	//2.加锁
	pipChan := make(chan bool, 1)
	var waitGroup sync.WaitGroup

	var count int
	for i := 1; i < 1000; i++ {
		//开启协程计数
		waitGroup.Add(1)
		go ResourceLock(pipChan, i, &count, &waitGroup)
	}
	//等待协程执行完毕
	waitGroup.Wait()
	close(pipChan)
	//fmt.Println(count)

	// 保证写成完成前，主进程没有终止
	for ii := 0; ii < 1; {
		ii = 0
	}
}

func ResourceLock(pip chan bool, i int, count *int, waitGroup *sync.WaitGroup) {
	//协程结束done
	defer waitGroup.Done()
	//不加锁就会小于1000
	pip <- true
	*count += i
	<-pip
}
